package com.foyekoo.project001.service;

import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.foyekoo.project001.activity.WelcomeActivity;
import com.foyekoo.project001.config.Config;
import com.foyekoo.project001.utils.DataTransfer;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

public class UsbHostService extends Service {

    private String TAG = this.getClass().getName();
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private UsbManager usbManager;
    private UsbDevice usbDevice = null;
    private UsbInterface[] usbInterfaces = null;
    private UsbEndpoint[][] usbEndpoints = new UsbEndpoint[5][5];
    private UsbDeviceConnection usbDeviceConnection = null;
    byte[] mybuffer = new byte[1024];
    private int   myDeviceId = 1155, myProductId = 22336;
    private DataTransfer dataTransfer = new DataTransfer(1024);
    private ConnectedThread connectedThread = null;
    private DrawContralThread drawContralThread = null;
    private WriteThread writeThread;
    private ReadThread readThread;

    private boolean threadControlCt = false;
    private boolean threadControlMt = false;
    private boolean threadSendData = false;




    public static final String ACIONT_DATA_RECIVE = "com.android.data.ACIONT_DATA_RECIVE";

    public static final String EXTRA_DATA = "com.android.data.EXTRA_DATA";

    public class MyBinder extends Binder {
        public UsbHostService getService() {
            return UsbHostService.this;
        }
    }

    private MyBinder binder = new MyBinder();
    private String data = "";
    private final Random generator = new Random();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(TAG, "onCreate");

        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Log.e(TAG, "get device list:" + usbManager);

        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            usbDevice = deviceIterator.next();
            Log.v(TAG, "vid:" + usbDevice.getVendorId() + "\t pid:" + usbDevice.getProductId());
            if (usbDevice.getVendorId() == myDeviceId && usbDevice.getProductId() == myProductId)
                break;
        }

        if (usbDevice != null && usbDevice.getVendorId() == myDeviceId && usbDevice.getProductId() == myProductId)
            data = "找到支持设备！\n设备ID号:" + usbDevice.getVendorId() + "\n产品ID号:" + usbDevice.getProductId();
        else
            data = "未找到支持设备！\n";

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        if (!usbManager.hasPermission(usbDevice))
            usbManager.requestPermission(usbDevice, pendingIntent);
        if (usbManager.hasPermission(usbDevice)) {
            data += "\n拥有访问权限！";
        } else {
            data += "\n未拥有访问权限！";
        }
        data += "\n设备名称：" + usbDevice.getDeviceName() + "\n端点数：" + usbDevice.getInterfaceCount();
        for(int i = 0;i < usbDevice.getInterfaceCount();i ++){
            usbInterfaces[i] = usbDevice.getInterface(i);
            for(int j = 0;j < usbInterfaces[i].getEndpointCount();j ++){
                usbEndpoints[i][j] = usbInterfaces[i].getEndpoint(j);
            }
        }

        for(int i = 0; i < usbDevice.getInterfaceCount();i ++){
            usbInterfaces[i] = usbDevice.getInterface(i);
            data += "\n接口" + i + "的端点数为：" + usbInterfaces[i].getEndpointCount();
            for(int j = 0;j < usbInterfaces[i].getEndpointCount();j ++){
                usbEndpoints[i][j] = usbInterfaces[i].getEndpoint(j);
                if(usbEndpoints[i][j].getDirection() == 0) {
                    data += "\n端点" + j + "的数据方向为输出";
                } else {
                    data += "\n端点" + j + "的数据方向为输入 ";
                }
            }
        }
        broadcastSend(Config.ACTION_USB_CONNECT, data);


        threadControlCt = true;

        if (connectedThread == null) {
            connectedThread = new ConnectedThread();
            connectedThread.start();;
        }


    }



    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy");
    }

    /**
     * 读Thread
     */
    private class ReadThread extends Thread{

    }

    /**
     * 写的线程
     */
    private class WriteThread extends Thread{
        @Override
        public void run() {
            super.run();
        }
    }

    private class ConnectedThread extends Thread {
        public ConnectedThread() {
            if (usbDeviceConnection != null) {
                usbDeviceConnection.close();
            }
            usbDeviceConnection = usbManager.openDevice(usbDevice);
            usbDeviceConnection.claimInterface(usbInterfaces[1], true);
            broadcastSend(Config.ACTION_USB_CONNECT, "连接成功了骚逼");
        }

        @Override
        public void run() {
            int dataLength;
            while (threadControlCt) {
                if (threadSendData) {
                    threadSendData = false;
                    //TODO
                    byte[] data = new byte[1024];
                    usbDeviceConnection.bulkTransfer(usbEndpoints[1][0], data, data.length, 30);
                }
                dataLength = usbDeviceConnection.bulkTransfer(usbEndpoints[1][1], mybuffer, 1024, 30);

                dataTransfer.AddData(mybuffer, dataLength);
                if (dataLength >= 0) {

                }
            }
        }
    }




    private class DrawContralThread extends Thread {
        @Override
        public void run() {
            while (threadControlMt) {
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    //发送广播
    private void broadcastSend(String config, String data) {
        sendBroadcast(new Intent(config).putExtra(config, data));
    }
}
